package cn.iocoder.yudao.module.fengdong.smartelderly.controller.app;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.accessrecord.AccessRecordDO;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.oldman.OldmanDO;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.reserved.ReservedDO;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.accessrecord.AccessRecordMapper;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.oldman.OldmanMapper;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.reserved.ReservedMapper;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.JsonUtils;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.QrCodeUtils;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.vo.ActivityRecordBaseVO;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.xingyuv.jushauth.utils.UuidUtils;
import io.swagger.v3.oas.annotations.Operation;
import jodd.io.FileUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId;

/**
 *
 * 门禁控制接口
 * ***/
@RestController
@RequestMapping("/access")
@Log4j2
public class AppAccessController {

    @Resource
    private MemberUserService userService;
    @Resource
    private ReservedMapper reservedMapper;

    @Resource
    private AccessRecordMapper accessRecordMapper;

    @Autowired
    QrCodeUtils qrCodeUtils;

    @Resource
    private OldmanMapper oldmanMapper;

    @PostMapping("/QueryCmd")
    @Operation(summary = "门禁心跳和远程操作")
    @OperateLog(enable = false) // 禁用操作日志，因为没有操作人
    public String QueryCmd(@RequestBody JSONObject params) {
        try {
            //接收到的数据格式  {ViewId=V123, UID=123, UKey=ABCD12345678, SN=2308609398, TamperAlarm=1, DoorMagnetic=1, Timestamp=1703067524, Sign=693bf2908a5a5f1e5c10365209d244c2}
            // log.info("QueryCmd:{}",body);
            //......以下写业务逻辑
            //................
            //返回数据
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int CmdCode = 0;//0为无命令，即心跳返回
            String CmdID = String.valueOf(System.currentTimeMillis());//CmdID可定义
            JSONObject jsonObj = new JSONObject();
            JSONObject jsonObjCmd0 = new JSONObject();
            jsonObjCmd0.put("DateTime", formatter.format(new Date()));//返回服务器时间给设备
            jsonObj.put("CmdID", CmdID);
            jsonObj.put("CmdCode", CmdCode);
            jsonObj.put("CmdParams", jsonObjCmd0);
            //无命令返回格式：{"CmdCode":0,"CmdID":"1601193461935","CmdParams":{"DateTime":"2020-09-27 15:57:41"}}
            // log.info("接口返回:{}",ret);
            return jsonObj.toJSONString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // System.out.println("Ex:" + e.getMessage());
        }
        return "";
    }

    @PostMapping("/CheckCode")
    @Operation(summary = "检测二维码权限")
    @OperateLog(enable = false) // 禁用操作日志，因为没有操作人
    public String CheckCode(@RequestBody JSONObject params) {
        try {
            //接收到的数据格式  {"CodeVal":"985","CodeType":"Q","BrushTime":"2020-09-24 09:17:21","ViewId":"1","UID":"123","UKey":"1234","SN":"170000001","IsOnline":"1","Property":"1","Timestamp":"1600910241600","Sign":"ed097d71179890af524759daacaea06f"}
            // CodeType数据类型
            // "Q"代表二维码；
            //"C"代表 IC 卡；
            //"I"代表身份证；
            //"B"代表出门按钮（对于票务板，代表出园计数，即 IN2 输入信号）；
            // CodeVal 可为二维码值，IC 卡卡号，身份证序号/身份证号码等
            //log.info("CheckCode:{}",params);
            //解析json
            String SN = params.getString("SN");//卡号
            //......以下写业务逻辑
            //................

            //返回数据
            JSONObject jsonObj = new JSONObject();

            Integer result=2;
//            Gson gson = new Gson();
//            ActivityRecordBaseVO recordBaseVO = gson.fromJson((String) params.get("CodeVal"), ActivityRecordBaseVO.class);
            String codeVal = (String) params.get("CodeVal");
            ActivityRecordBaseVO recordBaseVO = JsonUtils.jsonToObj(codeVal, ActivityRecordBaseVO.class);
            log.info("二维码数据:{}",recordBaseVO);
            if (null!=recordBaseVO) {
                setTenantId(recordBaseVO.getTenantId());
                if (recordBaseVO.getUserType()!=null && recordBaseVO.getUserId()!=null) {
                    log.info("进入校验");
                    result = validateAdmin(recordBaseVO);
                }
            }
            // 1合法 2非法
            jsonObj.put("Status", result);
            // 屏幕显示信息（可选）
            // jsonObj.put("StatusDesc", "验票成功\r\n请进");
            // 继电器动作时间（毫秒）（可选）
            // jsonObj.put("Relay1Time", 1000);
            // 可开闸次数（可选）
            // jsonObj.put("TurnGateTimes", 1);
            String ret = jsonObj.toJSONString(); //返回格式：{"Status":1,"StatusDesc":"验票成功\r\n请进","TurnGateTimes":1,"Relay1Time":1000}
            System.out.println("Return CheckCode:" + ret);
            return ret;
        } catch(Exception e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            System.out.println("Ex:" + e.getMessage());
        }
        return "";
    }

    private  Integer validateAdmin(ActivityRecordBaseVO recordBaseVO) {
        Integer result = 2;
        //内部人员   查询该人员状态是否正常
        if (recordBaseVO.getUserType()!=null && recordBaseVO.getUserType()==1) {
            MemberUserDO user = userService.getUser(recordBaseVO.getUserId());
            if (user!=null && user.getStatus()==0) {
                //管理员状态 为启用
                result=1;
            }
        }
        if (recordBaseVO.getActivityKind()!=null){
            if (recordBaseVO.getActivityKind()==3) {
                //请假外出 查询用户审核记录
                List<OldmanDO> doList = oldmanMapper.selectOldmanExBytype(recordBaseVO);
                log.info("该老人请假审核通过数"+doList.size());
                if (doList.size()>0) {
                    AccessRecordDO accessRecordDO = new AccessRecordDO();
                    accessRecordDO.setActivityKind(recordBaseVO.getActivityKind());
                    accessRecordDO.setUserId(recordBaseVO.getUserId());
                    Long count = accessRecordMapper.selectCount(new LambdaQueryWrapperX<AccessRecordDO>()
                            .eqIfPresent(AccessRecordDO::getActivityKind, recordBaseVO.getActivityKind())
                            .eqIfPresent(AccessRecordDO::getUserId, recordBaseVO.getUserId()));
                    if (count % 2 == 0) {
                        //出去
                        accessRecordDO.setContent("出去");
                    }else {
                        //进入
                        accessRecordDO.setContent("进入");
                    }
                    //老人请假通过 放行
                    result=1;
                }
            }else if (recordBaseVO.getActivityKind()==2) {
                //探视 查询用户审核记录
                List<ReservedDO> doList = reservedMapper.selectUserExBytype(recordBaseVO);
                log.info("该用户探视审核通过数"+doList.size());
                if (doList.size()>0) {
                    if (recordBaseVO.getReservedId()!=null) {
                        long count = doList.stream()
                                .filter(reservedDO -> reservedDO.getId() == recordBaseVO.getReservedId())
                                .count();
                        if (count>0) {
                            //用户探视通过 放行
                            result=1;
                        }
                    }
                }
            }else if (recordBaseVO.getActivityKind()==1 && recordBaseVO.getIdentityCard()!=null) {
                //访客 查询用户审核记录
                List<OldmanDO> doList = oldmanMapper.selectFkExBytype(recordBaseVO);
                log.info("该访客请假审核通过数"+doList.size());
                if (doList.size()>0) {
                    //访客 通过 放行
                    result=1;
                }
            }
        }

        return result;
    }

    @PostMapping("/getQrCode")
    @Operation(summary = "生成二维码")
    @OperateLog(enable = false) // 禁用操作日志，因为没有操作人
    public String getQrCode(@RequestBody ActivityRecordBaseVO activityRecordBaseVO) throws Exception {
        //生成二维码
        return  qrCodeUtils.getQrCode(activityRecordBaseVO);
    }

    @PostMapping("/Localtest")
    @Operation(summary = "生成二维码")
    @OperateLog(enable = false) // 禁用操作日志，因为没有操作人
    public File getQrCodeLocaltest(@RequestBody ActivityRecordBaseVO activityRecordBaseVO) {
        String uuid = UuidUtils.getUUID();
        //生成二维码
        String content= JsonUtils.objToJson(activityRecordBaseVO);
        File generate = QrCodeUtil.generate(
                content, //二维码数据
                300,
                300,
                FileUtil.file("c:/tp/"+uuid+".jpg"));
        return  generate;
    }
}
